#pragma once
#include <windows.h>

#define BUF_SIZE 0x2000000

TCHAR szName[] = TEXT("trex_shared_memory_");
HANDLE hMapFile;
LPVOID pBuf;
LPTSTR lpMapName;

BOOL CreateSharedMemory(LPTSTR lpName)
{
	lpMapName = lpName;
	hMapFile = CreateFileMapping(
		INVALID_HANDLE_VALUE,
		NULL,
		PAGE_READWRITE,
		0,
		BUF_SIZE,
		lpName
	);
	if (hMapFile == NULL)
		return FALSE;
	pBuf = MapViewOfFile(
		hMapFile,
		FILE_MAP_ALL_ACCESS,
		0,
		0,
		BUF_SIZE
	);
	if (pBuf == NULL)
		CloseHandle(hMapFile);
	return pBuf != NULL;
}

BOOL ReadSharedMemory(UCHAR* buffer, ULONG offset)
{
	size_t size = _msize(buffer);
	HANDLE hMapFile = OpenFileMapping(
		FILE_MAP_ALL_ACCESS,
		FALSE,
		lpMapName
	);
	if (hMapFile == NULL)
		return FALSE;
	UCHAR* pBuf = (UCHAR*)MapViewOfFile(
		hMapFile,
		FILE_MAP_ALL_ACCESS,
		0,
		0,
		BUF_SIZE
	);
	if (pBuf == NULL)
	{
		CloseHandle(hMapFile);
		return FALSE;
	}
	memcpy(buffer, &pBuf[offset], size);
	return UnmapViewOfFile(pBuf) && CloseHandle(hMapFile);
}

BOOL WriteSharedMemory(UCHAR* buffer, ULONG offset)
{
	size_t size = _msize(buffer);
	HANDLE hMapFile = OpenFileMapping(
		FILE_MAP_ALL_ACCESS,
		FALSE,
		lpMapName
	);
	if (hMapFile == NULL)
		return FALSE;
	UCHAR* pBuf = (UCHAR*)MapViewOfFile(
		hMapFile,
		FILE_MAP_ALL_ACCESS,
		0,
		0,
		BUF_SIZE
	);
	if (pBuf == NULL)
	{
		CloseHandle(hMapFile);
		return FALSE;
	}
	memcpy(&pBuf[offset], buffer, size);
	return UnmapViewOfFile(pBuf) && CloseHandle(hMapFile);
}

void CloseSharedMemory()
{
	UnmapViewOfFile(pBuf);
	CloseHandle(hMapFile);
}

/*
printf("\n    | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F |");
printf("\n-------------------------------------------------------------------------\n");
for (int i = 0; i < 512; i += 16)
{
	printf("%04X: ", i);
	for (int j = 0; j < 16; j++)
	{
		printf("%02X ", pBuf[i + j]);
	}
	printf("\n");
}
*/
